package com.bian.springboot04thymeleaf.controller;

import com.bian.springboot04thymeleaf.dao.DepartmentDao;
import com.bian.springboot04thymeleaf.dao.EmployeeDao;
import com.bian.springboot04thymeleaf.entities.Department;
import com.bian.springboot04thymeleaf.entities.Employee;
import groovy.util.logging.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import java.util.Collection;
import java.util.Map;

/**
 * @author bianpengfei
 * @create 2019-01-30 16:23
 **/
@Slf4j
@Controller
public class EmployeeController {

    @Autowired
    private EmployeeDao employeeDao;

    @Autowired
    private DepartmentDao departmentDao;

    /**
     * 查询所有员工返回列表页面
     * */
    @GetMapping("/emps")
    public String list(Model model) {
        Collection<Employee> employees = employeeDao.getAll();

        // 放在请求域中
        model.addAttribute("emps", employees);

        // Thymeleaf默认会拼串
        return "emps/list";
    }

    /**
     * 员工添加页面
     * */
    @GetMapping("/emp")
    public String toAddPage(Map<String, Object> map) {
        // 来到添加页面,查出所有部门信息，在页面显示
        Collection<Department> departments = departmentDao.getDepartments();
        map.put("depts", departments);
        return "emps/add";
    }

    /**
     * 员工添加
     * SpringMvc自动将请求参数和入参对象那个属性进行一一绑定，要求请求参数的名字和javaBean入参的属性名是一样的
     * */
    @PostMapping("/emp")
    public String addEmp(Employee employee) {

        System.out.println(employee);
        employeeDao.save(employee);
        //来到员工列表页面
        // redirect 表示重定向到一个地址 /表示当前路径
        // forward 表示转发一个地址
        return "redirect:/emps";
    }

    /**
     * 来到修改页面，查出当前员工，在页面回显
     * */
    @GetMapping("/emp/{id}")
    public String toEditPage(@PathVariable("id") Integer id,Model model) {
        System.out.println(id);
        Employee employee = employeeDao.get(id);
        model.addAttribute("emp", employee);

        // 页面要显示所有的部门列表
        Collection<Department> departments = departmentDao.getDepartments();
        model.addAttribute("depts", departments);
        // 回到修改页面（add是一个修改和添加二合一的）
        return "emps/add";
    }

    /**
     * 员工修改
     * */
    @PutMapping("/emp")
    public String updateEmp(Employee employee) {
        System.out.println(employee);
        employeeDao.save(employee);
        return "redirect:/emps";
    }

    /**
     * 员工删除
     * */
    @DeleteMapping("/emp/{id}")
    public String deleteEmp(@PathVariable("id")Integer id) {
        employeeDao.delete(id);
        return "redirect:/emps";
    }
}
